//
//  BuildingViewController.m
//  3DModelCollector
//
//  Created by Jing Zhang on 7/7/12.
//  Copyright (c) 2012 Tencent. All rights reserved.
//

#import "BuildingViewController.h"
#import "BasicInfoEditController.h"
#import "PhotoViewController.h"
#import "PhotoInfo.h"
#import "Utility.h"
#import "TakePhotoController.h"
#import "SelectPhotoController.h"

@interface BuildingViewController ()

@property (retain, nonatomic) IBOutlet UIView *basicInfoView;
@property (retain, nonatomic) IBOutlet UIView *photoInfoView;

@property (retain, nonatomic) IBOutlet BuildingOverview *overview;
@property (nonatomic, retain) NSMutableArray* photoViewList;
@property (nonatomic, retain) NSMutableArray* filterPhotoList;

@property (nonatomic)   int sideIndex;

- (IBAction)onSelectInfoType:(id)sender;
- (IBAction)onClickEdit:(id)sender;
- (IBAction)onClickMissionImpossibleButton:(id)sender;
- (IBAction)onClickViewPhoto:(id)sender;
- (void)onClickSaveBarButton:(id)sender;

- (void)onTapPhoto:(UIGestureRecognizer*)gestureRecognizer;
- (void)onTapAddPhoto:(UIGestureRecognizer*)gestureRecognizer;

- (void)selectSide:(int)index;
- (void)updatePhotoInfo:(NSArray*)photoList;
- (void)addImageToContainer:(UIImage*)image photoInfo:(PhotoInfo*)info;
- (NSString*)formatBasicInfo;
- (NSString*)formatPhotoInfo:(PhotoInfo*)info;

@end

@implementation BuildingViewController

@synthesize basicInfoView = _basicInfoView;
@synthesize photoInfoView = _photoInfoView;
@synthesize overview = _overview;

@synthesize photoViewList = _photoViewList;
@synthesize filterPhotoList = _filterPhotoList;

@synthesize building = _building;
@synthesize sideIndex = _sideIndex;

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
        self.title = @"Building";
        UIBarButtonItem* saveBarButton = [[UIBarButtonItem alloc] initWithTitle:@"保存" style:UIBarButtonItemStyleBordered target:self action:@selector(onClickSaveBarButton:)];
        self.navigationItem.rightBarButtonItem = saveBarButton;
        [saveBarButton release];
        
        NSMutableArray* array = [[NSMutableArray alloc] initWithCapacity:1];
        self.photoViewList = array;
        [array release];
        
        // Fake data
        Building* oneBuilding = [Building createExperimentalBuilding];
        self.building = oneBuilding;
        [oneBuilding release];
        
        self.overview.delegate = self;
    }
    return self;
}

- (void)dealloc {
    self.building = nil;
    self.photoViewList = nil;
    self.filterPhotoList = nil;
    [_basicInfoView release];
    [_photoInfoView release];
    [_overview release];
    [super dealloc];
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    
    [self updateBuildingBasicInfo:self.building.basicInfo];
    [self selectSide:0];
//    [self updatePhotoInfo:self.building.photoInfoList];
    
    self.overview.building = self.building;
}

- (void)viewDidUnload
{
    [self setBasicInfoView:nil];
    [self setPhotoInfoView:nil];
    self.photoViewList = nil;
    [self setOverview:nil];
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
}

- (void)viewWillAppear:(BOOL)animated {
    
    [super viewWillAppear:animated];
    
    if (self.overview != nil) {
        self.overview.locationEnabled = YES;
    }
}

- (void)viewWillDisappear:(BOOL)animated {
    
    [super viewWillDisappear:animated];
    
    if (self.overview != nil) {
        self.overview.locationEnabled = NO;
    }
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}

#pragma mark - [UIActionSheetDelegate]

- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex {
    
    // 拍照
    if (buttonIndex == actionSheet.destructiveButtonIndex) {
      
        TakePhotoController* takePhotoController = [[TakePhotoController alloc] initWithNibName:@"TakePhotoController" bundle:nil];
        PhotoInfo* newPhotoInfo = [[PhotoInfo alloc] init];
        newPhotoInfo.purposeFlag = BS_Gate | BS_StoreyCounter;
        newPhotoInfo.attachedSideIndex = 2;
        takePhotoController.photoInfo = newPhotoInfo;
        takePhotoController.photoInfoList = self.building.photoInfoList;
        takePhotoController.photoDelegate = self;
        [newPhotoInfo release];
        UINavigationController* navController = [[UINavigationController alloc] initWithRootViewController:takePhotoController];
        navController.navigationBarHidden = YES;
        [self.navigationController presentModalViewController:navController animated:YES];
        [navController release];
        [takePhotoController release];
    }
    // 使用已有照片
    else if (buttonIndex == 1) {
        
        SelectPhotoController* selectController = [[SelectPhotoController alloc] initWithNibName:@"SelectPhotoController" bundle:nil];
        selectController.photoInfoList = self.building.photoInfoList;
        [self.navigationController presentModalViewController:selectController animated:YES];
        
        NSLog(@"User existed");
    }
}

#pragma mark - [UpdateBuildingBasicInfoDelegate]

- (void)updateBuildingBasicInfo:(BuildingBasicInfo *)basicInfo {
    
    self.building.basicInfo = basicInfo;
    
    NSString* basicInfoText = [self formatBasicInfo];
    UITextView* basicTextView = (UITextView*)[self.basicInfoView viewWithTag:1];
    basicTextView.text = basicInfoText;
}

#pragma mark - [DeletePhotoDelegate]

- (void)deletePhoto:(int)index {
    
    if (index < 0 || index >= self.building.photoInfoList.count) {
        return;
    }
    
    [self.building.photoInfoList removeObjectAtIndex:index];
    
    // 更新界面
    UIImageView* delImageView = (UIImageView*)[self.photoViewList objectAtIndex:index];
    [delImageView removeFromSuperview];
    
    [UIView beginAnimations:nil context:nil];
    [UIView setAnimationDuration:0.4f];
    for (int i = index + 1; i < self.photoViewList.count; i++) {
        UIImageView* view = [self.photoViewList objectAtIndex:i];
        CGRect frame = view.frame;
        frame.origin.x -= 74;
        view.frame = frame;
    }
    
    UIScrollView* thumbPhotoContainer = (UIScrollView*)[self.photoInfoView viewWithTag:2];
    UIImageView* addImageView = (UIImageView*)[thumbPhotoContainer viewWithTag:10];
    CGRect addImageFrame = addImageView.frame;
    addImageFrame.origin.x -= 74;
    addImageView.frame = addImageFrame;
    
    [UIView commitAnimations];
    
    [self.photoViewList removeObjectAtIndex:index];
}

#pragma mark - [AddPhotoDelegate]

- (void)addPhoto:(UIImage *)photo description:(PhotoInfo *)info {
    
    // 写文件
    
    // 更新建筑物图片数据
    
    
    // 更新界面    
    UIScrollView* photoContainer = (UIScrollView*)[self.photoInfoView viewWithTag:2];
    
    int photoNum = self.building.photoInfoList.count;
    photoContainer.contentSize = CGSizeMake((photoNum + 2) * 74, 60);
    [self addImageToContainer:photo photoInfo:info];
    
    UIImageView* addImageView = (UIImageView*)[photoContainer viewWithTag:10];
    CGRect addImageFrame = addImageView.frame;
    addImageFrame.origin.x += 74;
    addImageView.frame = addImageFrame;
    
    NSLog(@"Add new photo!");
}

#pragma mark - [AddExistedPhotoDelegate]

- (void)addExistedPhoto:(UIImage *)photo description:(PhotoInfo *)info {
    
    NSLog(@"Add existed photo!");
}

#pragma mark - [SelectSideDelegate]

- (void)onSelectSide:(int)index {
    
    NSLog(@"Select side : %d", index);
    
    if (index < 0 || index >= self.building.baseIndiceList.count) {
        return;
    }
    
    // Change
    NSNumber* indexObj = [NSNumber numberWithInt:index];
    [self performSelector:@selector(selectSide:) withObject:indexObj afterDelay:0.3f];
}

#pragma mark - [Private methods]

- (void)onClickSaveBarButton:(id)sender {
    
    NSLog(@"Save");
}

- (IBAction)onSelectInfoType:(id)sender {
    
    UISegmentedControl* selector = (UISegmentedControl*)sender;
    if (selector.selectedSegmentIndex == 0) {
        self.basicInfoView.hidden = NO;
        self.photoInfoView.hidden = YES;
    }
    else {
        self.basicInfoView.hidden = YES;
        self.photoInfoView.hidden = NO;
    }
}

- (IBAction)onClickEdit:(id)sender {
    
    BasicInfoEditController* basicInfoEditController = [[BasicInfoEditController alloc] init];
    basicInfoEditController.basicInfo = self.building.basicInfo;
    basicInfoEditController.delegate = self;

    UINavigationController* navController = [[UINavigationController alloc] initWithRootViewController:basicInfoEditController];
    [self.navigationController presentModalViewController:navController animated:YES];
    [basicInfoEditController release];
    [navController release];
}

- (IBAction)onClickMissionImpossibleButton:(id)sender {
}

- (IBAction)onClickViewPhoto:(id)sender {
    
    PhotoViewController* photoViewController = [[PhotoViewController alloc] initWithNibName:@"PhotoViewController" bundle:nil];
    photoViewController.photoList = self.building.photoInfoList;
    photoViewController.curIndex = 0;
    photoViewController.delegate = self;
    UINavigationController* navController = [[UINavigationController alloc] initWithRootViewController:photoViewController];
    [self.navigationController presentModalViewController:navController animated:YES];
    [navController release];
    [photoViewController release];
}

- (void)onTapPhoto:(UIGestureRecognizer *)gestureRecognizer {
    
    UIView* targetView = gestureRecognizer.view;
    
    int photoNum = self.photoViewList.count;
    for (int i = 0; i < photoNum; i++) {
        UIView* view = [self.photoViewList objectAtIndex:i];
        if (view == targetView) {
            PhotoViewController* photoViewController = [[PhotoViewController alloc] initWithNibName:@"PhotoViewController" bundle:nil];
            photoViewController.photoList = self.building.photoInfoList;
            photoViewController.curIndex = 0;
            photoViewController.delegate = self;
            UINavigationController* navController = [[UINavigationController alloc] initWithRootViewController:photoViewController];
            [self.navigationController presentModalViewController:navController animated:YES];
            [navController release];
            [photoViewController release];
            
            break;
        }
    }
}

- (void)onTapAddPhoto:(UIGestureRecognizer *)gestureRecognizer {
    
    // To do
    UIActionSheet* actionSheet = [[UIActionSheet alloc] initWithTitle:nil delegate:self cancelButtonTitle:@"取消" destructiveButtonTitle:@"拍照" otherButtonTitles:@"选择已有照片", nil];
    [actionSheet showInView:self.view];
    [actionSheet release];
}

- (void)selectSide:(int)index {
    
    if (self.sideIndex == index) {
        return;
    }
    
    self.sideIndex = index;
    
    // Filter the photo by side
    
}

- (void)updatePhotoInfo:(NSArray *)photoList {
    
    [self.photoViewList removeAllObjects];
    
    UIScrollView* thumbPhotoContainer = (UIScrollView*)[self.photoInfoView viewWithTag:2];
    int photoNum = photoList.count;
    thumbPhotoContainer.contentSize = CGSizeMake((photoNum + 1) * 74, 60);
    
    for (int i = 0; i < photoNum; i++) {
        PhotoInfo* onePhoto = [photoList objectAtIndex:i];
        NSString* fullPhotoFileName = [NSString stringWithFormat:@"%@/%@.jpg", @"", onePhoto.name];
        UIImage* image = [UIImage imageWithContentsOfFile:fullPhotoFileName];
        if (image == nil) {
            continue;
        }
        
        [self addImageToContainer:image photoInfo:onePhoto];
    }
    
    // 添加“添加”按钮
    CGRect addImageViewRect;
    addImageViewRect.origin.x = 74 * photoNum + 7;
    addImageViewRect.origin.y = 0;
    addImageViewRect.size.width = 60;
    addImageViewRect.size.height = 60;
    
    UIImageView* addImageView = [[UIImageView alloc] initWithFrame:addImageViewRect];
    addImageView.tag = 10;
    addImageView.userInteractionEnabled = YES;
    addImageView.image = [UIImage imageNamed:@"add_photo"];
    
    UITapGestureRecognizer* addImageGesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(onTapAddPhoto:)];
    [addImageView addGestureRecognizer:addImageGesture];
    [addImageGesture release];
    
    [thumbPhotoContainer addSubview:addImageView];
    [addImageView release];
}

- (NSString*)formatBasicInfo {
    
    NSMutableString* text = [NSMutableString stringWithCapacity:256];
    
    [text appendFormat:@"ID:%d\n", self.building.basicInfo.UID];
    [text appendFormat:@"名称:%@\n", self.building.basicInfo.name];
    [text appendFormat:@"地址:%@\n", self.building.basicInfo.address];
    [text appendFormat:@"类型:%u\n", self.building.basicInfo.type];
    [text appendFormat:@"底座真实度:%@\n", [Utility baseAccuracyToString:self.building.basicInfo.type]];
    [text appendFormat:@"区划:%@\n", self.building.basicInfo.division];
    [text appendFormat:@"商圈:%@\n", self.building.basicInfo.businessRegion];
    if (![self.building.basicInfo.remark isEqualToString:@""]) {
        [text appendFormat:@"备注:%@\n", self.building.basicInfo.remark];
    }
    [text appendFormat:@"%@", [Utility dateToString:self.building.basicInfo.lastModifieTime]];
    
    return text.description;
}

- (NSString*)formatPhotoInfo:(PhotoInfo*)info {
    
    NSMutableString* text = [NSMutableString stringWithCapacity:256];
    
    // 用途
    [text appendFormat:@"用途:"];
    for (int i = BS_StoreyCounter; i <= BS_UpperTexture; i++) {
        if ((info.purposeFlag & i) != 0) {
            NSString* str = [Utility buildingTypeToString:i];
            [text appendFormat:@"%@ ", str];
        }
    }
    [text appendString:@"\n"];
    
    // 坐标
    [text appendFormat:@"坐标:%.6f, %.6f\n", info.coordinate.longitude, info.coordinate.latitude];
    
    // 时间
    [text appendFormat:@"时间:%@", info.timeStamp.description];
    
    return @"";
}

- (void)addImageToContainer:(UIImage *)image photoInfo:(PhotoInfo *)info {
    
    int photoNum = self.building.photoInfoList.count;

    UIScrollView* photoContainer = (UIScrollView*)[self.photoInfoView viewWithTag:2];
    
    CGRect thumbRect;
    if (image.size.width < image.size.height) {
        thumbRect.size.height = 60;
        thumbRect.size.width = image.size.width * 60.0 / image.size.height;
        thumbRect.origin.x = 74 * photoNum + (74 - thumbRect.size.width) / 2;
        thumbRect.origin.y = 4;
    }
    else {
        thumbRect.size.width = 60;
        thumbRect.size.height = image.size.height * 60.0 / image.size.width;
        thumbRect.origin.x = 74 * photoNum + 7;
        thumbRect.origin.y = (60 - thumbRect.size.height) / 2;
    }
    
    UIImageView* newImageView = [[UIImageView alloc] initWithFrame:thumbRect];
    newImageView.userInteractionEnabled = YES;
    // To do 2 : 可以考虑压缩成略缩图，以节省内存
    newImageView.image = image;
    
    // 添加点击事件响应
    UITapGestureRecognizer* tapGestureRecognizer = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(onTapPhoto:)];
    [newImageView addGestureRecognizer:tapGestureRecognizer];
    [tapGestureRecognizer release];
    
    // 添加至滚动视图
    [photoContainer addSubview:newImageView];
    [newImageView release];
    
    [self.photoViewList addObject:newImageView];
    //    [newImageView release];
    
    [self.building.photoInfoList addObject:info];
}

@end
